package com.xkdx.caipiao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xkdx.caipiao.cost.CostRechargeActivty;
import com.xkdx.caipiao.listener.OnAlertDialogOkListener;
import com.xkdx.caipiao.my.FlowRechargeActivity;
import com.xkdx.caipiao.wiget.MyAlertDialog;
import com.xkdx.guangguang.BrandActivity;
import com.xkdx.guangguang.CardActivity;
import com.xkdx.guangguang.CityActivity;
import com.xkdx.guangguang.DayRecommendActivity;
import com.xkdx.guangguang.LoginActivity;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.ShopActivity;
import com.xkdx.guangguang.UserActivity;
import com.xkdx.guangguang.application.MyApplication;
import com.xkdx.guangguang.fragment.city.CityAction;
import com.xkdx.guangguang.fragment.city.CityModule;
import com.xkdx.guangguang.fragment.city.CityPresistence;
import com.xkdx.guangguang.fragment.my.setup.UpdateVerisonAction;
import com.xkdx.guangguang.fragment.my.setup.UpdateVersionModule;
import com.xkdx.guangguang.fragment.my.setup.UpdateVersionModule.Startup;
import com.xkdx.guangguang.fragment.my.setup.UpdateVersionPresistener;
import com.xkdx.guangguang.fragment.user.UserSharePrefence1;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.presistence.uploaddevicetoken.UpLoadDeviceTokenAction;
import com.xkdx.guangguang.presistence.uploaddevicetoken.UpLoadDeviceTokenModule;
import com.xkdx.guangguang.presistence.uploaddevicetoken.UpLoadDeviceTokenPresistence;
import com.xkdx.guangguang.pushserviceforSelf.PushForSelfInfo;
import com.xkdx.guangguang.shareclass.BrandDetail;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class HomePageActivity extends ManagerActivity implements
        OnClickListener, OnAlertDialogOkListener {
    private TextView cityNameTxt;
    // public static LoginInfo loginInfo;
    private RelativeLayout goToWifi, goToCaiPiao, goToPhone, goToShop, goToHui;
    UpLoadDeviceTokenModule module;
    UpLoadDeviceTokenAction action;
    UpLoadDeviceTokenPresistence presistence;
    SharePrefenceUtil su;
    SharePrefenceUtil su_brand;
    private UserSharePrefence1 userInfo;
    UpdateVerisonAction updateVerisonAction;
    UpdateVersionModule updateVersionModule;
    UpdateVersionPresistener updateVersionPresistener;
    private SharePrefenceUtil su_city;
    public static List<BrandDetail> upDateBrandlist;
    PushForSelfInfo pushInfo = null;
    CityPresistence cityPresistence;
    CityAction cityAction;
    CityModule cityModule;
    public static List<Map<String, String>> cityList;
    private static final int REFRESH_CITY_DELAY = 500;
    private Handler mCityHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_update_caipiao);
        init();
        // loginInfo = getLoginInfo();
        userInfo = new UserSharePrefence1(this, IConstants.SP_USER_NEW);

        su_brand = new SharePrefenceUtil(this, IConstants.SP_BRAND);
        su = new SharePrefenceUtil(this, "isUpLoadToken");
        su_city = new SharePrefenceUtil(this, IConstants.SP_CITY);
        action = new UpLoadDeviceTokenAction(this,
                su_brand.getBrandUpdateTime());
        module = new UpLoadDeviceTokenModule();
        presistence = new UpLoadDeviceTokenPresistence(this);
        presistence.setActitons(action);
        presistence.setModule(module);
        presistence.execute();

        Bundle b = getIntent().getExtras();
        if (b != null) {

            pushInfo = (PushForSelfInfo) b.getSerializable("pushself");
            if (pushInfo != null && !("".equals(pushInfo.getObjectType()))) {
                IConstants.isHasSelfPush = pushInfo.isSelfNotificationState();
                // IConstants.isFromSelf = false;
                ProData(pushInfo);
            }
        }

        checkVersion();
        getCityInfo();
    }
    
    private Runnable refreshCity = new Runnable() {
        @Override
        public void run() {
            if(MyApplication.isLocating){
                mCityHandler.postDelayed(refreshCity,REFRESH_CITY_DELAY);
            }else{
                refreshCityName();
            }
        }
    };

    private void init() {
        goToWifi = (RelativeLayout) findViewById(R.id.go_to_wifi);
        goToCaiPiao = (RelativeLayout) findViewById(R.id.go_to_caipiao);
        goToPhone = (RelativeLayout) findViewById(R.id.go_to_phone);
        goToShop = (RelativeLayout) findViewById(R.id.go_to_shop);
        goToHui = (RelativeLayout) findViewById(R.id.go_to_hui);
        cityNameTxt = (TextView) findViewById(R.id.city_name_txt);

        findViewById(R.id.go_to_brand).setOnClickListener(this);
        findViewById(R.id.go_to_me).setOnClickListener(this);
        findViewById(R.id.go_to_recommend).setOnClickListener(this);
        findViewById(R.id.native_lacation).setOnClickListener(this);
        goToWifi.setOnClickListener(this);
        goToCaiPiao.setOnClickListener(this);
        goToPhone.setOnClickListener(this);
        goToShop.setOnClickListener(this);
        goToHui.setOnClickListener(this);
    }

    private void checkVersion() {
        updateVerisonAction = new UpdateVerisonAction(this);
        updateVersionModule = new UpdateVersionModule();
        updateVersionPresistener = new UpdateVersionPresistener(this);
        updateVersionPresistener.setActitons(updateVerisonAction);
        updateVersionPresistener.setModule(updateVersionModule);
        updateVersionPresistener.execute();
    }

    public void refreshCityInfo(HashMap<String, AbsModule> result) {
        if (result.containsKey("0")) {
            cityList = cityModule.cityList;
        }
    }

    /**
     * 刷新定位城市名称
     */
    private void refreshCityName(){
        if(IConstants.isChoiceCity){
            cityNameTxt.setText(su_city.getChoiceCityName());
        }else if(IConstants.isLocationSuccess){
            cityNameTxt.setText(su_city.getLocationCityName());
        }else if(MyApplication.isLocating){
            mCityHandler.removeCallbacks(refreshCity);
            mCityHandler.postDelayed(refreshCity,REFRESH_CITY_DELAY);
        }
    }

    private void getCityInfo() {
        cityPresistence = new CityPresistence(this);
        cityAction = new CityAction();
        cityModule = new CityModule();
        addCurrentTask(cityPresistence);
        cityPresistence.setActitons(cityAction);
        cityPresistence.setModule(cityModule);
        cityPresistence.execute();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_to_wifi:
                startIntent(FlowRechargeActivity.class);
                break;
            case R.id.go_to_caipiao:
                startIntent(MainTabActivity.class);
                break;
            case R.id.go_to_phone:
                startIntent(CostRechargeActivty.class);
                break;
            case R.id.go_to_shop:
                startIntent(ShopActivity.class);
                break;
            case R.id.go_to_brand:
                startIntent(BrandActivity.class);
                break;
            case R.id.go_to_me:
                if (!(TextUtils.isEmpty(userInfo.getLogintoken()))) {
                    startIntent(MyStrollActivity.class);
                } else {
                    Intent loginIntent = new Intent(this,LoginActivity.class);
                    startActivityForResult(loginIntent,LoginActivity.LOGIN_REQUEST);
                }
                break;
            case R.id.go_to_hui:
                startIntent(CardActivity.class);
                break;
            case R.id.go_to_recommend:
                startIntent(DayRecommendActivity.class);
                break;
            case R.id.native_lacation:
                startIntent(CityActivity.class);
                break;
            default:
                break;
        }
        // case R.id.ll_mygg:
        //
        // loginInfo = getLoginInfo();
        // if (loginInfo != null
        // && !(TextUtils.isEmpty(loginInfo.getLogintoken()))) {
        // Intent inten2 = new Intent(this, MyStrollActivity.class);
        // startActivity(inten2);
        // } else {
        // Intent inten3 = new Intent(this, Login.class);
        // startActivity(inten3);
        // }
        //
        // break;

    }

    private void ProData(PushForSelfInfo pushInfo) {

        int type = Integer.valueOf(pushInfo.getObjectType());
        // String value = pushInfo.getObjectValue();
        if (type == 1) {
            // IConstants.isHasSelfPush = false;
        } else if (type == 2) {
            // IConstants.isHasSelfPush = false;
            IConstants.download(this, "dl.guangguang.net.cn/GuangGuang.apk");
        }
        // case 3:
        // HomeDetailFragment detail = new HomeDetailFragment();
        // Bundle b3 = new Bundle();
        // b3.putString("infoID", value);
        // detail.setArguments(b3);
        // getSupportFragmentManager().beginTransaction()
        // .replace(R.id.fragment, detail).addToBackStack(null)
        // .commitAllowingStateLoss();
        // break;
        // case 4:
        // ShopInfoFragment info = null;
        // if (info == null) {
        // info = new ShopInfoFragment();
        // }
        // Bundle b4 = new Bundle();
        // b4.putString("shopID", value);
        // info.setArguments(b4);
        // getSupportFragmentManager().beginTransaction()
        // .replace(R.id.fragment, info).addToBackStack(null)
        // .commitAllowingStateLoss();
        // break;
        // case 5:
        // BranchFragment branchFragment = new BranchFragment();
        // Bundle b5 = new Bundle();
        // b5.putString("shopID", value);
        // branchFragment.setArguments(b5);
        // getSupportFragmentManager().beginTransaction()
        // .replace(R.id.fragment, branchFragment)
        // .addToBackStack(null).commitAllowingStateLoss();
        // break;
        // case 6:
        // BrandInfoFragment brandInfo = new BrandInfoFragment();
        // Bundle b6 = new Bundle();
        // b6.putString("brandID", value);
        // brandInfo.setArguments(b6);
        // getSupportFragmentManager().beginTransaction()
        // .replace(R.id.fragment, brandInfo).addToBackStack(null)
        // .commitAllowingStateLoss();
        // break;
        // case 7:
        // NewsFragment newsFragment = new NewsFragment();
        // Bundle b7 = new Bundle();
        // b7.putString("infoID", value);
        // newsFragment.setArguments(b7);
        // getSupportFragmentManager().beginTransaction()
        // .replace(R.id.fragment, newsFragment).addToBackStack(null)
        // .commitAllowingStateLoss();
        //
        // break;
        // case 8:
        // DiscountFragment discountInfo = new DiscountFragment();
        // Bundle b8 = new Bundle();
        // b8.putString("infoID", value);
        // discountInfo.setArguments(b8);
        // getSupportFragmentManager().beginTransaction()
        // .replace(R.id.fragment, discountInfo).addToBackStack(null)
        // .commitAllowingStateLoss();
        //
        // break;
        else {
            Intent intent4 = new Intent(this, UserActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("pushself", pushInfo);
            IConstants.selfInfo = pushInfo;
            startActivity(intent4);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        setIntent(intent);
        // Toast.makeText(getApplicationContext(), "onnewintent", 0).show();

        if (intent != null) {
            Bundle b = getIntent().getExtras();
            if (b != null) {

                pushInfo = (PushForSelfInfo) b.getSerializable("pushself");
                if (pushInfo != null && !("".equals(pushInfo.getObjectType()))) {
                    IConstants.isHasSelfPush = pushInfo
                            .isSelfNotificationState();
                    ProData(pushInfo);
                }
                
                if(b.getBoolean(LoginActivity.JUMPTOME)){
                	Intent loginIntent = new Intent(this,MyStrollActivity.class);
                	startActivity(loginIntent);
                }
            }
            
            
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // loginInfo = getLoginInfo();
        refreshCityName();
        if (pushInfo == null) {
            if (IConstants.isHasPush) {
                int type = Integer.valueOf(IConstants.objectType);
                if (type == 1) {
                    IConstants.isHasPush = false;
                } else if (type == 2) {
                    IConstants.isHasPush = false;
                    IConstants.download(this,
                            "dl.guangguang.net.cn/GuangGuang.apk");
                } else {
                    IConstants.BottomBtnSelected = 5;
                    Intent intent4 = new Intent(this, UserActivity.class);
                    startActivity(intent4);
                }

            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mCityHandler.removeCallbacks(refreshCity);
    }

    public void showLoaded(HashMap<String, AbsModule> map) {
        if (map.containsKey("0")) {
            if (module.isSucess) {
                su.setIsUpLoadToken(true);
            }
            su_brand.setBrandUpdateTime(module.updateTime);
            upDateBrandlist = module.list;
        }

    }

    public void versionCheckedOver(HashMap<String, AbsModule> map) {
        if (map.containsKey("0")) {
            final Startup startup = updateVersionModule.startup;
            if (startup.getClientUpdate().equals("True")) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        HomePageActivity.this);
                builder.setTitle("有新版本,是否更新");
                builder.setNegativeButton("是",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                IConstants.download(HomePageActivity.this,
                                        startup.getClientDownloadUrl());
                            }
                        });
                builder.setPositiveButton("否", null);
                builder.create().show();
            }

        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getRepeatCount() == 0) {
                showTips();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private void showTips() {

        MyAlertDialog.creatAlertDialog(HomePageActivity.this, "退出提示",
                "确定退出逛逛生活?");
        MyAlertDialog.setOnAlertDialogOklistener(this);

    }

    @Override
    public void handleOkClick() {
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());

    }

    @Override
    public void handleDismissClick() {
        // TODO Auto-generated method stub

    }

    private void startIntent(Class a) {
        Intent inten = new Intent(HomePageActivity.this, a);
        startActivity(inten);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LoginActivity.LOGIN_REQUEST && resultCode == LoginActivity.LOGIN_SUCCESS) {
            startIntent(MyStrollActivity.class);
        }

    }
}
